#!/bin/sh -eu

# Copyright (c) 2017-2021 Tim Ruehsen
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

# First step: In the top directory execute
# export CC=clang-5.0
# export CFLAGS="-O1 -fno-omit-frame-pointer -gline-tables-only -DFUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION -fsanitize=address -fsanitize-address-use-after-scope -fsanitize-coverage=trace-pc-guard,trace-cmp"
# ./configure --enable-static --disable-gtk-doc --enable-runtime=libidn2 --enable-builtin=libidn2
# make clean
# make -j$(nproc) LIB_FUZZING_ENGINE="-lFuzzer"
# cd fuzz
# make -j$(nproc) check

#
# Read the docs at https://github.com/google/oss-fuzz/blob/master/docs/corpora.md
# then install 'google-cloud-sdk' and execute 'gcloud init'.
# Now 'gsutil' should be ready to use.

if test -z "$1"; then
  echo "Usage: $0 <fuzzer target>"
  echo "Example: $0 libidn2_to_ascii_8z_fuzzer"
  exit 1
fi

fuzzer=$1
project=$(echo $1 | cut -d'_' -f1)

# sync/copy the OSS-Fuzz corpora into the .new directory
mkdir -p ${fuzzer}.new
cp -p ${fuzzer}.in/* ${fuzzer}.new
gsutil cp $(gsutil ls gs://${project}-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/${fuzzer}|tail -n 1) ${fuzzer}.new
(cd ${fuzzer}.new && unzip -q -f -o *.zip && rm *.zip)

# create fuzzer target
BUILD_ONLY=1 ./run-clang.sh ${fuzzer}

# merge the corpora into the .in directory
./${fuzzer} -merge=1 ${fuzzer}.in ${fuzzer}.new

# now clear .new dir and put all corpora there
rm -f ${fuzzer}.new/*
mv ${fuzzer}.in/* ${fuzzer}.new

# now merge again (optimizes number of corpora)
./${fuzzer} -merge=1 ${fuzzer}.in ${fuzzer}.new

echo
echo "If new files have been added, 'git add' and 'git commit' them."
